package org.atguigu.config;

import org.atguigu.filter.CaptchaFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.DefaultSecurityFilterChain;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

//开启方法权限检查
@EnableMethodSecurity(prePostEnabled = true)
@Configuration
public class SecurityConfig {
    @Autowired
    CaptchaFilter captchaFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 配置安全过滤器链
     *
     * @return
     */
    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
        //设置登录页面路径
        DefaultSecurityFilterChain defaultSecurityFilterChain = httpSecurity
                //登录页面
                .formLogin((formLogin) -> {
                    formLogin
                            //url要与页面登录按钮的action地址相同
                            .loginProcessingUrl("/user/login")
                            //去登录页面
                            .loginPage("/toLogin")
                            //定制登录成功的行为,默认情况下spring security框架是跳转到登录前所访问的地址
                            .successForwardUrl("/welcome");
                })
                //登出页面
//                .logout((logout) -> {
//                    logout.logoutUrl()
//                })
                .authorizeHttpRequests((authorizeHttpRequests) -> {
                    authorizeHttpRequests.requestMatchers("/toLogin", "/common/captcha").permitAll() // /toLogin允许未登录就可以访问
                            .anyRequest().authenticated();//所有请求都需要认证(登录)
                })
                //验证码校验的filter加到用户名密码校验前面
                .addFilterBefore(captchaFilter, UsernamePasswordAuthenticationFilter.class)
                .build();

        return defaultSecurityFilterChain;
    }
}
